<script setup lang="ts">
import type { SelectOption } from 'naive-ui'
import { reactive, watch } from 'vue'
import { isMobileMode } from '@/utils/detection'
import { storeToRefs } from 'pinia'
import { useModelStore } from '@/stores/model'
import ChangeModel from '@/components/ChangeModel.vue'

// 模型存储
const modelStore = useModelStore()
const { readActiveModelInfo } = storeToRefs(modelStore)

// 定义事件
const emits = defineEmits(['change-model'])

// 状态参数
const state = reactive({
  // 当前模型key
  modelKey: '',
  // 当前模型名称,
  modelName: '',
})

// 切换模型
const onChangeModel = (option: SelectOption) => {
  modelStore.changeActiveModel(option.value as string)
}

// 监听：模型变更
watch(
  readActiveModelInfo,
  (model) => {
    state.modelKey = model?.id ?? ''
    state.modelName = model?.name ?? ''
    // 处理额外显示模型名称
    if (state.modelName && !isMobileMode()) {
      // 手机模式宽度有限，不显示
      if (model?.supplier?.name) {
        // 显示分组名称
        state.modelName = state.modelName + ' (' + model.supplier.name + ')'
      }
    }
    emits('change-model', {
      id: state.modelKey,
      name: state.modelName,
    })
  },
  {
    immediate: true,
  },
)
</script>
<template>
  <ChangeModel
    type="llm"
    v-model:value="state.modelKey"
    use-popselect
    show-setting
    @change="onChangeModel"
  />
</template>
<style lang="scss" scoped></style>
